package com.community.property.controller;

import java.util.*;

import com.community.common.utils.minio.MinioUtils;

import com.community.property.domain.Repair;
import com.community.property.domain.VO.RepairVO;
import com.community.property.service.IRepairService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.community.common.annotation.Log;
import com.community.common.core.controller.BaseController;
import com.community.common.core.domain.AjaxResult;
import com.community.common.enums.BusinessType;
import com.community.common.utils.poi.ExcelUtil;
import com.community.common.core.page.TableDataInfo;


/**
 * 报修管理Controller
 *
 * @author ruoyi
 * @date 2025-10-27
 */
@RestController
@RequestMapping("/property/repair")
@Slf4j
public class RepairController extends BaseController {
    @Autowired
    private IRepairService repairService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 统计待处理报修
     */
    @GetMapping("/count")
    public AjaxResult count(){
        return success(repairService.count());
    }
    /**
     * 查询报修管理列表
     */
    @PreAuthorize("@ss.hasPermi('property:repair:list')")
    @GetMapping("/list")
    public TableDataInfo list(Repair repair) {
        startPage();
        List<Repair> list = repairService.selectRepairList(repair);
        return getDataTable(list);
    }

    /**
     * 导出报修管理列表
     */
    @PreAuthorize("@ss.hasPermi('property:repair:export')")
    @Log(title = "报修管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Repair repair) {
        List<Repair> list = repairService.selectRepairList(repair);
        ExcelUtil<Repair> util = new ExcelUtil<Repair>(Repair.class);
        util.exportExcel(response, list, "报修管理数据");
    }

    /**
     * 获取报修管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('property:repair:query')")
    @GetMapping("/{repairId}")
    public AjaxResult getInfo(@PathVariable("repairId") Integer repairId) {
        return success(repairService.selectRepairByRepairId(repairId));
    }

    /**
     * 新增报修管理
     */

    @Autowired
    private ObjectMapper objectMapper; // 添加这行

    /**
     * 新增报修管理
     */
    @PreAuthorize("@ss.hasPermi('property:repair:add')")
    @Log(title = "报修管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Repair repair) {
        // 确保状态设置为1（待分配）
        repair.setStatus(1);

        // 先保存报修信息
        int result = repairService.insertRepair(repair);

        if (result > 0) {
            // 发送延迟消息到MQ（30秒后检查状态）
            try {
                // 创建简单的消息内容
                Map<String, Object> simpleMessage = new HashMap<>();
                simpleMessage.put("repairId", repair.getRepairId());
                simpleMessage.put("originalStatus", 1); // 明确设置为1
                simpleMessage.put("businessType", "CHECK_REPAIR_STATUS");
                simpleMessage.put("timestamp", System.currentTimeMillis());

                // 发送到普通队列，30秒后会自动转到死信队列
                rabbitTemplate.convertAndSend("repair.exchange", "repair.add", simpleMessage);

                log.info("✅ 报修延迟消息已发送到MQ，报修ID: {}, 当前状态: 1, 30秒后自动检查状态", repair.getRepairId());

            } catch (Exception e) {
                log.error("❌ 发送报修延迟消息到MQ失败", e);
            }
        }

        return toAjax(result);
    }

    /**
     * 调试接口：检查MQ状态
     */
    @Autowired
    private RabbitMQDebugger rabbitMQDebugger;
    @GetMapping("/debug/mq")
    public AjaxResult debugMQ() {
        try {
            rabbitMQDebugger.checkQueueStatus();
            return success("MQ状态检查完成，请查看日志");
        } catch (Exception e) {
            return error("MQ状态检查失败: " + e.getMessage());
        }
    }



    /**
     * 修改报修管理
     */
    @PreAuthorize("@ss.hasPermi('property:repair:edit')")
    @Log(title = "报修管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Repair repair) {
        return toAjax(repairService.updateRepair(repair));
    }

    /**
     * 删除报修管理
     */
    @PreAuthorize("@ss.hasPermi('property:repair:remove')")
    @Log(title = "报修管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{repairIds}")
    public AjaxResult remove(@PathVariable Integer[] repairIds) {
        return toAjax(repairService.deleteRepairByRepairIds(repairIds));
    }



    @GetMapping("/lookStream")
    @Log(title = "报修进度")
    public TableDataInfo lookStream() {

        List<RepairVO> list = repairService.lookStream();

        return getDataTable(list);
    }


}
